import React from 'react';
import { connect } from 'react-redux';
import { Row, Col, Transfer } from 'antd';
import { fetchUsers } from "../../../actions/usersActions";
import "./style.css";

var dataSource = [];
var targetKeys = [];
class UsersTransfer extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      sourceData:[],
      selectedKeys: [],
    };
  }

  componentWillMount(){
    this.loadUsers() ;
  }

  loadUsers  = () => {
    const users = this.state.sourceData  ; 
    if ( users.length < 1 ) {
      this.props.fetchUsers("email").then(
          (data) => {  this.wrapData("users",data,"email");this.setState({type:"users"});   },
          (err) => {  console.log(err);  }
         );
    }
  }

  wrapData = (type,sourceData,title) => {
    var data = this.state.sourceData ;
    if (!sourceData) {
      data = [];
    }else{
        for ( let i =0 ; i < sourceData.length ; i++) {
          data.push({
            key: sourceData[i].id,
            title: sourceData[i][title],
            description: ``,
          });
      }
    }
    dataSource = data;
  }

  handleChange = (keys) => {
      targetKeys = keys ; 
      this.props.onChange(keys);
  }

  render() {
   if ( this.props.value ) {
       targetKeys = this.props.value ;
   }
    return (
        <div id="users-selector">
          <Row>
            <Col span={10}>
              <Transfer
                showSearch
                dataSource={dataSource}
                titles={['Source', 'Target']}
                targetKeys={targetKeys}
                onChange={this.handleChange}
                render={item => item.title}
                listStyle={{
                  width: 250,
                  height: 300,
                }}
              />
            </Col>
          </Row>
        </div>
    );
  }
}

UsersTransfer.propTypes = {
    fetchUsers: React.PropTypes.func.isRequired,
    value: React.PropTypes.array.isRequired,
};

const mapStateToProps = (state) => {
  return {
     users: state.user.users,
   }
}

export default connect(mapStateToProps,{ fetchUsers})(UsersTransfer);